package com.atguigu.config;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.entity.Admin;
import com.atguigu.service.AdminService;
import com.atguigu.service.PermissionService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author 杨林
 * @create 2022-09-30 13:35 星期五
 * description:通过实现UserDetailsService接口的方式来提供用户认证授权信息
 */
@Component
public class MyUserDetailService implements UserDetailsService {

    @Reference
    private AdminService adminService;

    @Reference
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //通过username来获取admin的信息
        Admin admin = adminService.getByUsername(username);

        if (admin == null){
            throw new UsernameNotFoundException("该用户名不存在！！");
        }

        Collection<GrantedAuthority> authorities = new ArrayList<>();
        //authorities.add(new SimpleGrantedAuthority("role.show"));
        //authorities.add(new SimpleGrantedAuthority("role.assgin"));

        //在真实的场景中 我们需要通过访问数据库来获取用户对应的权限
        List<String> codeList = permissionService.findCodeListByAdminId(admin.getId());
        for (String code : codeList) {
            authorities.add(new SimpleGrantedAuthority(code));
        }


        User user = new User(username,admin.getPassword(),authorities);

        //只需要返回user即可 spring security 进行密码的比较 如果登录成功授予authorities权限
        return user;
    }
}
